package com.mentalhealthplatform.studentV3.service;

import com.mentalhealthplatform.appModels.BookingLecture;
import com.mentalhealthplatform.appModels.Lecture;
import com.mentalhealthplatform.global.rbac.model.CustomUserDetails;
import com.mentalhealthplatform.global.rbac.model.User;
import com.mentalhealthplatform.global.rbac.service.UserDetailsServiceImpl;
import com.mentalhealthplatform.studentV3.repository.BookingLectureRepositoryV3;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author Pear
 */
@Service
public class BookingLectureServiceV3 {

    @Autowired
    private BookingLectureRepositoryV3 bookingLectureRepositoryV3;

    @Autowired
    private LectureServiceV3 lectureServiceV3;

    @Autowired
    private UserDetailsServiceImpl userDetailsService;

    // 通过电话号码查询预约信息
    public List<BookingLecture> findByPhone(String phone) {
        return bookingLectureRepositoryV3.findByPhone(phone);
    }

    // 通过讲座ID查询预约信息
    public List<BookingLecture> findByLectureId(Long lectureId) {
        return bookingLectureRepositoryV3.findByLectureId(lectureId);
    }

    // 根据 ID 查找预约记录是否存在
    public boolean existsById(Long id) {
        return bookingLectureRepositoryV3.existsById(id);
    }

    // 根据 ID 删除预约记录
    public void deleteById(Long id) {
        // 获取当前认证的用户信息
        CustomUserDetails currentUserDetails = (CustomUserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        User currentUser = currentUserDetails.getUser();


        // 检查是否存在该预约记录
        BookingLecture bookingLecture = bookingLectureRepositoryV3.findById(id)
                .orElseThrow(() -> new IllegalArgumentException("预约记录不存在"));

        // 验证预约记录的电话号码是否与当前用户的电话号码匹配
        if (!bookingLecture.getPhone().equals(currentUser.getPhone())) {
            throw new IllegalArgumentException("您无权删除此预约记录");
        }

        // 如果电话号码匹配，删除预约记录
        bookingLectureRepositoryV3.deleteById(id);
    }

    // 根据 ID 查找预约记录
    public BookingLecture findById(Long id) {
        return bookingLectureRepositoryV3.findById(id).orElse(null);
    }

    // 创建预约
    public BookingLecture createBookingLecture(BookingLecture bookingLecture) {
        if (bookingLecture.getLecture() != null && bookingLecture.getLecture().getId() != null) {
            // 通过Lecture ID查询对应的Lecture对象
            Lecture lecture = lectureServiceV3.findById(bookingLecture.getLecture().getId())
                    .orElseThrow(() -> new IllegalArgumentException("讲座不存在"));
            // 设置预约的讲座对象
            bookingLecture.setLecture(lecture);
        }

        return bookingLectureRepositoryV3.save(bookingLecture);
    }
}
